package com.smartrobot.smartrobot.websocket;

import android.content.Context;
import android.util.Log;
import com.loopj.android.http.*;
import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.User;
import org.apache.http.Header;
import org.json.JSONObject;

/**
 * Created by yeluojun on 2015/1/12.
 */
public class Util {


    //socket服务器帮助登录
    public static void loginWithNoHandler(final Context context){

         AsyncHttpClient aClient = new SyncHttpClient();
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        aClient.setCookieStore(cookieStore);


        RequestParams params = new RequestParams();

        if( User.getInstance() == null){
            User.getUserInfo(context);
        }
        if(User.getInstance().getPhone()==null||User.getInstance().getPhone().equals("未填写")){
            LogToSd.log_init();
            LogToSd.info("socket登录：用户信息丢失");
            stopWebsocketServer(); //停止socket
            return;
        }

        params.put("userAccount", User.getInstance().getPhone());
        params.put("userPassword", User.getInstance().getPwd());

        aClient.post(Common.baseUrl+"/login_commonUse", params, new JsonHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);


                socketUtil.initSocket_2(context);

                LogToSd.log_init();
                LogToSd.info("socket 登录成功");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }

        });

    }



    //停止webSocket服务
    public static void stopWebsocketServer(){

        try{
            heatBeat.setBreakHeart(false); //关闭心跳
            Common.startHeartBeat = false;
            Common.startWebSocketServer = false; //关闭websocket服



            if( Common.my_webSocketClient.isConnected()){  //关闭websocket连接
                Common.my_webSocketClient.disconnect();
            }

            Common.my_webSocketClient = null;   //重置数据
            Common._websocketHandler2 = null;   //重置数据
        }catch (Exception e){
            Log.e("websocket util stopWebsocketServer:",e.toString());
            LogToSd.log_init();
            LogToSd.error("websocket util stopWebsocketServer:" + e.toString());
        }
    }

    public static void startWebsocketServer(){
        heatBeat.setBreakHeart(true); //开启心跳
        Common.startHeartBeat = true; //开启心跳
        Common.startWebSocketServer = true; //开始websocket服务
    }
}
